<template>
  <el-drawer
    :title="title"
    :visible.sync="drawer"
    :direction="direction"
    :before-close="handleClose"
    custom-class="drawerClass"
    destroy-on-close
    size="90%"
  >
    <!--            签收方式下拉组件-->

    <el-form
      class="form"
      ref="form"
      :model="entity"
      label-width="100px"
      :rules="rules"
    >
      <div class="mask" v-if="title == '编辑订单'"></div>
      <el-row> </el-row>

      <el-row :gutter="20">
        <el-col v-for="item in formList" :key="item.Id" :span="8">
          <el-form-item :label="item.Key" :prop="item.Keys">
            <el-input
              v-model="entity[item.Keys]"
              v-if="item.isFormTrue == 'false'"
            ></el-input>
            <!-- @select="CompanyShipperSelect($event, item)" -->

            <CompanyShipper
              v-if="item.isFormTrue == 'true' && item.Keys == 'CarrierId'"
              @select="CompanyShipperSelect($event, item)"
              v-model="entity[item.Keys]"
              :CompanyId="Company"
            >
            </CompanyShipper>
            <!-- :disabled="item.isAddTrue == 'false'" -->

            <CompanySearchSelect
              v-if="item.isFormTrue == 'true' && item.Keys == 'Company'"
              :disabled="true"
              @select="CompanySelect($event, item)"
              v-model="entity[item.Keys]"
            />
            <!-- :disabled="item.isAddTrue == 'false'" -->
            <CustomerSearchSelect
              v-if="item.isFormTrue == 'true' && item.Keys == 'CustomerName'"
              @select="CustomerSelect($event, item)"
              :CompanyId="Company"
              v-model="entity[item.Keys]"
            />
            <ContactPersonSearhSelect
              v-if="item.isFormTrue == 'true' && item.Keys == 'ContactPersonId'"
              :CompanyId="Company"
              :cCusCode="entity.CustomerId"
              v-model="entity[item.Keys]"
              @select="ContactPersonSelect($event, item)"
            />
            <!-- :disabled="item.isAddTrue == 'false'" -->
            <el-date-picker
              v-if="item.type == 6 && item.isFormTrue == 'true'"
              style="width: 100%"
              v-model="entity[item.Keys]"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>

            <!--            <el-radio-group v-model="entity.SignType" >-->
            <!--              <el-radio-button label="3">微信签收</el-radio-button>-->
            <!--              <el-radio-button label="0">二要素</el-radio-button>-->
            <!--              <el-radio-button label="2">三要素</el-radio-button>-->
            <!--              <el-radio-button label="1">人脸识别</el-radio-button>-->
            <!--            </el-radio-group>-->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-tabs v-model="activeName">
      <el-tab-pane label="货品信息" name="first">
        <div v-for="(item, index) in tableDataList" :key="item.Id">
          <h2
            style="
              display: flex;
              align-items: center;
              justify-content: end;
              border-bottom: 1px solid #ccc;
              margin: 0;
              padding: 0 8px 8px 8px;
            "
          >
            <div>
              <el-button type="primary" @click="handleWrit">选择货品</el-button>
              <el-button
                icon="el-icon-plus"
                type="primary"
                @click="handleAdd(index)"
                >增行</el-button
              >
            </div>
          </h2>
          <el-table :data="item.datalist" style="width: 100%" :max-height="600">
            <el-table-column
              v-for="(im, ix) in item.columns"
              :key="im.dataIndex"
              :prop="im.dataIndex"
              :label="im.title"
              v-if="im.dataIndex != 'nums'"
            >
              <template slot-scope="scope">
                <div v-if="im.dataIndex == 'Number'">
                  {{ scope.$index + 1 }}
                </div>
                <div v-else-if="im.dataIndex == 'xj1' || im.dataIndex == 'xj2'">
                  {{ scope.row[im.dataIndex] }}
                </div>
                <el-input
                  v-else
                  :type="im.type ? im.type : 'text'"
                  :maxlength="im.maxlength ? im.maxlength : ''"
                  v-model="scope.row[im.dataIndex]"
                  @input="handleChange(scope.row, im, scope.$index, ix)"
                ></el-input>
              </template>
              <!-- <template slot-scope="scope">
                <el-input
                  v-if="im.actionCol == '1'"
                  v-model="scope.row[im.dataIndex]"
                  @input="handleChange(scope.row[im.dataIndex], scope.row, im)"
                  type="number"
                  :min="1"
                >
                </el-input>
                <el-input
                  v-else-if="im.dataIndex === 'Quantity'"
                  v-model="scope.row[im.dataIndex]"
                  type="number"
                  :min="1"
                >
                </el-input>
                <el-input
                  v-else-if="
                    im.dataIndex === 'Batch' ||
                    (im.dataIndex === 'cInvName' && title == '编辑订单')
                  "
                  v-model="scope.row[im.dataIndex]"
                  type="
                    text
                  "
                >
                </el-input>
                <span
                  v-else-if="
                    im.dataIndex === 'cInvName' ||
                    im.dataIndex === 'cInvStd' ||
                    im.dataIndex === 'Weight' ||
                    im.dataIndex === 'Weight1' ||
                    im.dataIndex === 'nums'
                  "
                  >{{ scope.row[im.dataIndex] }}</span
                >
                <el-input v-else v-model="scope.row[im.dataIndex]"></el-input>
              </template> -->
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <!-- <i class="el-icon-connection iconStyle"></i> -->
                <!-- <el-button type="text" @click="handleWrit(index, scope)"
                  >选择货品</el-button
                > -->
                <el-button
                  slot="reference"
                  type="text"
                  @click="handleCopy(scope, index)"
                  >复制</el-button
                >
                <el-popconfirm
                  title="确定要删除本条货品吗?"
                  @confirm="handleDelete(scope, index)"
                >
                  <el-button class="warnBtn" slot="reference" type="text"
                    >删除</el-button
                  >
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="jsoncontent.isAccessory" label="附件" name="second">
        <div class="imgs">
          <div
            class="avatar-uploader"
            v-for="(url, inx) in fileList"
            :key="inx"
          >
            <i @click="delImgs(inx)" class="el-icon-delete del-icon"></i>
            <el-image
              @click="handlePictureCardPreview(url)"
              style="width: 100%; height: 100%"
              :src="url"
              fit="contain"
            ></el-image>
          </div>

          <el-upload
            v-if="fileList.length <= 9"
            class="avatar-uploader add-btn"
            :action="$baseUrl + '/Base_Manage/Upload/UploadFileUserByForm'"
            :show-file-list="false"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
            :headers="{
              Authorization: '',
            }"
          >
            <i class="el-icon-plus add-icon"></i>
          </el-upload>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <div style="height: 50px"></div>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 99999,
      }"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="display: flex">
          <div style="padding-right: 10px; margin-bottom: 20px">
            <span style="padding-right: 15px; font-size: 11px">认证方式</span>
            <el-radio-group
              v-model="entity.SignType"
              style="padding-right: 10px"
              @change="SignTypeChange"
              size="mini"
            >
              <!--              <el-radio-button label="0" :disabled="disabled0"-->
              <!--                ><span style="font-size: 11px">二要素</span></el-radio-button-->
              <!--              >-->
              <el-radio-button label="2" :disabled="disabled2"
                ><span style="font-size: 11px">三要素</span></el-radio-button
              >
              <el-radio-button label="1" :disabled="disabled1"
                ><span style="font-size: 11px">人脸识别</span></el-radio-button
              >
              <el-radio-button label="3" :disabled="disabled3"
                ><span style="font-size: 11px"
                  >仅微信认证</span
                ></el-radio-button
              >
              <!--              暂时去掉-->
              <!--              <el-radio-button label="4" :disabled="disabled4"-->
              <!--                ><span style="font-size: 11px">验证码</span></el-radio-button-->
              <!--              >-->
            </el-radio-group>
            <el-popover
              placement="top-start"
              title="签收方式"
              width="400"
              trigger="hover"
            >
              <span>微信签收: 签收人在使用微信签收时可直接对回执单进行签收</span
              ><br />
              <span>二要素：签收人在首次签收前需进行姓名及身份证号验证;</span
              ><br />
              <span
                >三要素：签收人在首次签收前需进行姓名、身份证号及手机号验证;</span
              ><br />
              <span>人脸识别：签收人在首次签收前需人脸识别验证验证;</span><br />
              <i slot="reference" class="el-icon-question question"></i>
            </el-popover>
          </div>
          <div style="margin-right: 20px">
            <span
              style="
                margin-left: 20px;
                displlay: inline-block;
                margin-right: 15px;
                font-size: 11px;
              "
              >发送方式</span
            >
            <!--            @change="SendTypeChange"  暂时去掉方法 后续根据需求-->
            <el-radio-group v-model="entity.SendType" size="mini">
              <el-radio-button label="0" :disabled="disabled5"
                ><span style="font-size: 11px"
                  >微信小程序</span
                ></el-radio-button
              >
              <el-radio-button label="1" :disabled="disabled6"
                ><span style="font-size: 11px">手机网页</span></el-radio-button
              >
            </el-radio-group>
          </div>
        </div>

        <div>
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </div>
    </div>
    <GoodsInfoSelect ref="goodsInfoSelect" @select="GoodsSelect" />
  </el-drawer>
</template>

<script>
import moment from "moment";
import { toThousands } from "@/utils/Tools";
import GoodsInfoSelect from "@/components/GoodsInfoSelect.vue";
import CompanySearchSelect from "@/components/CompanySearchSelect.vue";
import CompanyShipper from "@/components/CompanyShipper.vue";
import CustomerSearchSelect from "@/components/CustomerSearchSelect.vue";
import ContactPersonSearhSelect from "@/components/ContactPersonSearhSelect.vue";
export default {
  components: {
    CompanySearchSelect,
    CustomerSearchSelect,
    ContactPersonSearhSelect,
    GoodsInfoSelect,
    CompanyShipper,
  },
  props: {
    parentObj: { type: Object },
  },
  computed: {
    rules() {
      var obj = {};

      this.formList.forEach((item) => {
        if (item.isrules) {
          obj[item.Keys] = [{ required: true, message: `请填写${item.Key}` }];
        }
      });
      return obj;
    },
  },
  data() {
    return {
      disabled0: false, //二要素禁用
      disabled1: false, //人脸识别禁用
      disabled2: false, //三要素禁用
      disabled3: false, //仅微信禁用
      disabled4: false, //验证码
      disabled5: false, //微信小程序
      disabled6: false, //手机网页
      drawer: false,
      direction: "rtl",
      entity: {},
      // rules: {
      //   CompanyName: [{ required: true, message: '请选择公司' }],
      //   CustomerName: [{ required: true, message: '请选择客户' }],
      //   BillId: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
      // },
      btnLoading: false,
      title: "",
      loading: false,
      timeout: null,
      tableDataList: [], // 表格组
      toThousands,
      formList: [], // 表单组
      tableIndex: 0, // 操作表格下标
      jsoncontent: {},
      Company: "",
      dataArrIndex: 0,
      activeName: "first",
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
    };
  },
  methods: {
    // 认证方式选择改变回调
    SignTypeChange(event) {
      if (event == 0 || event == 2) {
        this.entity.SendType = "";
        // 如果点击的是二要素 或者三要素    通过微信或者手机网页都可以
        this.disabled5 = false;
        this.disabled6 = false;
      } else if (event == 1) {
        // 如果点击的是人脸识别  只能是通过手机网页获取 禁用仅微信 自动选中 通过手机网页获取
        this.entity.SendType = 1;
        this.disabled5 = true;
        this.disabled6 = false;
      } else if (event == 3) {
        this.entity.SendType = 0;
        //   如果点击的是仅微信认证    只能是通过微信获取  禁用人脸  自动选中通过微信获取
        this.disabled5 = false;
        this.disabled6 = true;
      }
    },
    //承运方选择
    CompanyShipperSelect(row, item) {
      this.entity.CarrierName = row.CarrierName;
      // this.entity.Company = row.Id
      item.value = row.CarrierName;
    },
    // 货品行件数变更
    handleChange(row, im, index, pIndex) {
      if (im.actionCol == "1") {
        // num:当前输入值;row:当前行;im:列数据
        let actionNum = 0;
        // 顺序依次 + - * /
        if (im.actionC == 0)
          actionNum = Number(row[im.actionA]) + Number(row[im.actionB]);
        else if (im.actionC == 1)
          actionNum = Number(row[im.actionA]) - Number(row[im.actionB]);
        else if (im.actionC == 2)
          actionNum = Number(row[im.actionA]) * Number(row[im.actionB]);
        else actionNum = Number(row[im.actionA]) / Number(row[im.actionB]);

        // 赋值
        row[im.actionD] = isNaN(actionNum) ? "" : actionNum.toFixed(2);
      }
      this.editData(row, im, index, pIndex);
    },
    editData(row, im, index, pIndex) {
      try {
        let sum = 0,
          num = 0;
        const templateList = [
          "w1",
          "w2",
          "w3",
          "w4",
          "w5",
          "w6",
          "w7",
          "w8",
          "w9",
          "w10",
        ];
        Object.keys(row).forEach((e) => {
          if (templateList.includes(e)) {
            if (row[e]) {
              let _sum = Number(row[e]);
              if (_sum < 0) {
                _sum = 0;
              }
              row[e] = _sum;
              sum += _sum;
              if (_sum) {
                num++;
              }
            }
          }
        });
        row.xj1 = num;
        row.xj2 = sum;
      } catch (e) {
        //TODO handle the exception
      }
    },
    // 货品选择
    GoodsSelect(rows) {
      let flag = false;
      rows.forEach((item) => {
        if (!Number(item.Weight)) {
          item.Weight = "";
        }
        if (!Number(item.iInvRCost)) {
          item.iInvRCost = "";
        } else {
          item.iInvRCost = Number(item.iInvRCost).toFixed(2).toString();
        }
        // 判断操作表格列是否已有该货品
        if (
          this.tableDataList[0].datalist.findIndex((im) => im.Id == item.Id) ==
          -1
        ) {
          // this.dataArrIndex++;
          this.tableDataList[0].datalist.unshift({
            ...JSON.parse(JSON.stringify(item)),
            Time: moment(new Date()).format("YYYY-MM-DD"),
          });
        } else {
          flag = true;
        }
      });
      if (flag) {
        this.$message.warning("相同货品已过滤");
      }
      //  else {
      //   this.tableDataList[0].datalist.splice(
      //     this.dataArrIndex,
      //     1
      //   );
      // }
    },
    // 表格新增
    // handleAdd(index) {
    //   if (!this.entity.CustomerId) return this.$message.error("请选择收货方");
    //   this.tableIndex = index;
    //   this.$refs.goodsInfoSelect.openForm(this.entity.CustomerId, this.Company);
    // },
    handleAdd(index) {
      this.tableDataList[0].datalist.unshift({});
    },
    // 表格行点击
    handleWrit(index, scope) {
      if (!this.entity.CustomerId) return this.$message.error("请选择收货方");
      // this.tableIndex = index;
      // this.dataArrIndex = scope.$index;
      this.$refs.goodsInfoSelect.openForm(this.entity.CustomerId, this.Company);
    },
    // 表格行删除
    handleDelete(scope, index) {
      console.log(scope, index);
      this.tableDataList[0].datalist.splice(scope.$index, 1);
      this.$message.success("操作成功");
    },
    handleCopy(scope, index) {
      let copyO = JSON.stringify(this.tableDataList[0].datalist[scope.$index]);
      this.tableDataList[0].datalist.splice(scope.$index, 0, JSON.parse(copyO));
    },
    // 公司选择 销售方
    CompanySelect(row, item) {
      console.log("公司选择组件回调方法--", row, item);
      this.entity.Sender = row.Title;
      // this.entity.Company = row.Id
      item.value = row.Title;
      // this.entity.CompanyName = row.Title;
      // this.$refs.form.clearValidate("CompanyName");
    },
    // 客户选择
    CustomerSelect(row, item) {
      console.log("新增客户选择好了", row, item);
      this.$set(this.entity, "Customer", row.cCusName);
      this.$set(this.entity, "CustomerId", row.Id);
      this.$set(this.entity, "Addres", row.cCusAddress);
      item.value = row.cCusName;

      // this.$refs.form.clearValidate("CustomerName");
      this.getSignTypeTheData(row.Id);
    },
    // 根据选择好的客户id判断签收方式
    getSignTypeTheData(id) {
      this.$http.post("/BO/CustomerInfo/GetTheData", { id: id }).then((res) => {
        if (res.Success) {
          console.log("根据选择客户id判断签收方式---", res.Data, this.entity);
          if (res.Data.SignType) {
            this.entity.SignType = String(res.Data.SignType);
          }
        }
      });
    },

    // 签收人选择
    ContactPersonSelect(row, item) {
      console.log("签收方式或者牵手选择人改变事件", row, item);
      this.entity.ContactPersonName = row.cName;
      this.entity.ContactPersonId = row.Id;
      this.entity.CustomerPhone = row.cPhone;
      item.value = row.cName;

      this.$refs.form.clearValidate("ContactPerson");
    },
    init() {
      this.entity = {
        // 发送方式和认证方式初始化
        SignType: "",
        SendType: "",
      };
      // 禁用初始化
      this.disabled0 = false;
      this.disabled1 = false;
      this.disabled2 = false;
      this.disabled3 = false;
      this.drawer = true;
      this.formList = [];
      this.tableDataList = [];
      this.fileList = [];
      // if (this.$refs['form']) {
      //   this.$refs['form'][0].resetField()
      // }
    },
    openForm(content, mode, Company, TemName, ContentId) {
      this.init();
      this.Company = Company;
      if (mode) {
        this.title = "编辑货单/服务";
        this.entity = content;
        console.log("获取攒底过来的货单详情content", this.entity);
        this.fileList =
          (this.entity.Attachment && this.entity.Attachment.split(",")) || [];
        // 处理签收方式数据类型
        if (this.entity.SignType !== null) {
          this.entity.SignType = "" + this.entity.SignType;
        }
        // 处理发送方式数据类型
        // 根据认证方式判断发送方式
        if (this.entity.SignType == 0 || this.entity.SignType == 2) {
          //   如果认证方式为二要素  三要素    微信和手机网页都可
          this.disabled5 = false;
          this.disabled6 = false;
        } else if (this.entity.SignType == 1) {
          //   如果认证方式为人脸识别  只能手机网页
          this.disabled5 = true;
          this.disabled6 = false;
        } else {
          //   如果认证方式为仅微信  只能微信小程序
          this.disabled5 = false;
          this.disabled6 = true;
        }

        console.log(
          "打印攒底过来的详情结果----------------------------------",
          content,
          this.entity.SendType,
          this.entity.SignType
        );
        var arr = JSON.parse(content.Content).printlist;
        this.jsoncontent = { ...JSON.parse(content.Content) };
        var arr2 = arr.filter((item) => {
          return !item.ispringt;
        });
        arr2.sort((a, b) => a.index - b.index);
        arr2.forEach((item) => {
          console.log(item.ispringt);
          this.$set(this.entity, item.Keys, item.value);
        });
        this.formList = arr2;

        console.log("打印arr2", arr2);
        this.tableDataList = arr.filter((item) => {
          return item.type === "4";
        });

        //   判断详情返回签收方式是否有值
        //   this.entity.SignType = this.entity.SignType ? this.entity.SignType :'3'
        console.log(
          "打印上面表单-------------------------------",
          this.formList
        );
      } else {
        this.title = "新增货单/服务";
        var arr = JSON.parse(content).printlist;
        this.jsoncontent = { ...JSON.parse(content) };
        var arr2 = arr.filter((item) => {
          return !item.ispringt;
        });
        arr2.sort((a, b) => a.index - b.index);
        arr2.forEach((item) => {
          if (item.Keys === "Company") {
            this.$set(item, "value", TemName);
            this.$set(this.entity, "Company", Company);
          } else {
            this.$set(item, "value", "");
          }
        });
        console.log(arr2, "123456");
        this.formList = arr2;
        this.tableDataList = arr.filter((item) => {
          return item.type === "4";
        });
        this.tableDataList.forEach((item) => {
          item.datalist = [];
        });

        console.log(arr2);
        // 获取公司发货地址
        this.$http
          .post("/Base_Manage/Base_Company/GetCommadders?compayid=" + Company)
          .then((res) => {
            if (res.Success && res.Data.length > 0) {
              this.$set(this.entity, "gongsiaddress", res.Data[0]);
            }
          });
        this.$set(this.entity, "BillId", new Date().getTime());
        this.$set(this.entity, "TemplateId", ContentId);
      }
    },
    handleClose(done) {
      done();
    },
    handleSubmit() {
      console.log(
        "开始校验了---------------",
        this.entity,
        this.entity.SignType,
        this.entity.SendType
      );
      // 如果没有选择发送方式 判断
      if (this.entity.SendType === "null" || this.entity.SendType === "") {
        console.log("走判断里了", this.entity.SignType);
        this.$message.error("请选择一种发送方式");
        return;
      }
      // 如果没有选择认证方式 判断
      if (this.entity.SignType === "null" || this.entity.SignType === "") {
        console.log("走判断里了", this.entity.SignType);
        this.$message.error("请选择一种认证方式");
        return;
      }

      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        let totalnumbers = 0, //数量合计
          totalweights = 0; //重量合计
        if (this.tableDataList.length > 0) {
          var arr = [];
          let emptyFlag = false;
          this.tableDataList.forEach((item) => {
            if (item.datalist.length == 0) {
              arr.push(item);
            } else {
              // // 检测需要合并项
              // let newarr = item.datalist.reduce((pre, cur) => {
              //   let idx = pre.findIndex((im) => {
              //     return (
              //       im.Id &&
              //       cur.Id &&
              //       im.Id == cur.Id &&
              //       im.Batch == cur.Batch &&
              //       im.cInvName &&
              //       cur.cInvName &&
              //       im.cInvName == cur.cInvName
              //     );
              //   });
              //   // 非重复项加入  重复项件数相加
              //   if (idx == -1) {
              //     pre.push(cur);
              //   } else {
              //     pre[idx].Quantity =
              //       Number(pre[idx].Quantity) + Number(cur.Quantity);
              //   }
              //   return pre;
              // }, []);
              // item.datalist = newarr;
            }
          });

          if (arr.length > 0) {
            return this.$message.error("请添加货品信息!");
          }
          //有未填项
          if (emptyFlag) {
            return this.$message.error("请补全货品信息!");
          }
        }
        var obj = { ...this.entity };
        this.formList.forEach((item) => {
          if (!item.value) {
            item.value = obj[item.Keys];
          }
        });
        let numflag = false;
        this.tableDataList.forEach((item) => {
          item.datalist.forEach((im, ix) => {
            im.Number = ix + 1;
            if (!im.Quantity || im.Quantity <= 0) {
              numflag = true;
            }
            im.cCusName = this.entity.Customer || "";
            if (!im.StatisticalQuantity) im.StatisticalQuantity = 0; // 数量
            if (!im.StatisticalWeight) im.StatisticalWeight = 0; // 重量
            if (!im.StatisticalPrice) im.StatisticalPrice = 0; // 价格
            // 所有件数相加
            im.StatisticalQuantity = isNaN(Number(im.Quantity))
              ? 0
              : Number(im.Quantity);
            // 件数乘单重相加
            im.StatisticalWeight =
              (isNaN(Number(im.Quantity)) ? 0 : Number(im.Quantity)) *
              (isNaN(Number(im.Weight)) ? 0 : Number(im.Weight));
            // 件数乘单价相加
            im.StatisticalPrice =
              (isNaN(Number(im.Quantity)) ? 0 : Number(im.Quantity)) *
              (isNaN(Number(im.iInvRCost)) ? 0 : Number(im.iInvRCost));
          });
        });
        // 暂时注释 否则无法保存 后续根据需求 修改此处
        // if (numflag)
        //   return this.$message.error("货品信息中存在未填写或小于零的数量");
        // JSON表单
        this.jsoncontent.printlist.forEach((item) => {
          this.formList.forEach((val) => {
            // console.log(val, item);
            if (item.Id === val.Id) {
              item.value = val.value;
            }
          });
          this.tableDataList.forEach((val2) => {
            if (item.Id === val2.Id) {
              item.value = val2.value;
              item.datalist = val2.datalist;
              item.columns = val2.columns;
            }
          });
        });
        this.entity.content = JSON.stringify(this.jsoncontent);
        // 主表内容
        this.entity.IP = sessionStorage.getItem("ip");
        this.entity.Company = this.Company;
        this.entity.Attachment = this.fileList.join(",");
        let url = "";
        if (this.title == "编辑货单/服务") {
          url = "/BO/BillList/UpdateDataBill";
          // this.entity.Status = -1;
        } else {
          url = "/BO/BillList/SaveData";
          this.entity.Status = 0;
        }
        this.btnLoading = true;
        console.log({
          data: this.entity,
          datalist: this.tableDataList[0].datalist,
        });
        this.entity.DomainName = "hzq";

        console.log("开始保存了", this.entity);
        // 表单保存
        this.$http
          .post(url, {
            data: this.entity,
            datalist: this.tableDataList[0].datalist,
          })
          .then((res) => {
            this.btnLoading = false;
            if (res.Success) {
              this.$message.success("操作成功");
              if (this.title == "编辑货单/服务") {
                this.drawer = false;
                this.parentObj.getDataList();
              } else {
                this.parentObj.getDataList();
                this.parentObj.queryParam.SupplieId = this.Company;
              }

              this.drawer = false;
            } else {
              this.$message.error(res.Msg);
            }
          });
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    handleImgSuccess(res, file) {
      if (res.status === "done") {
        // this.$emit("change", {
        //   img: res.url
        // });
        this.fileList.push(res.url);
      } else {
        this.$message.error("上传失败,请重试");
      }
      this.loading.close();
    },
    beforeImgUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      console.log(file.size / 1024);
      let isLt2M = file.size / 1024 < 5000;
      console.log(isLt2M);

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG或者PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过5M!");
        return false;
      }

      this.loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        color: "#fff",
        background: "rgba(0, 0, 0, 0.3)",
      });
      if (isJPG && isLt2M) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
              const canvas = document.createElement("canvas");
              const ctx = canvas.getContext("2d");
              console.log(img.width, img.height);
              const ratio = img.width / img.height;
              const baseSize = 500; //原始宽度值
              canvas.width = baseSize; // 设置压缩后图片的宽度
              // canvas.height = 300; // 根据原始图片比例计算压缩后图片的高度
              canvas.height = baseSize / ratio; // 根据原始图片比例计算压缩后图片的高度
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
              canvas.toBlob((blob) => {
                const compressedFile = new File([blob], file.name, {
                  type: file.type,
                  lastModified: Date.now(),
                });
                resolve(compressedFile);
              }, file.type);
            };
          };
        });
      }
      return isJPG && isLt2M;
    },
    delImgs(index) {
      this.fileList = this.fileList.filter((url, inx) => inx != index);
    },
  },
};
</script>

<style lang="less" scoped>
.iconStyle {
  color: #409eff;
}

.form {
  position: relative;
  padding-right: 10px;

  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 10;
    // background: #00000010;
  }
}

.warnBtn {
  color: red;
  margin-left: 8px;
}
.el-tab-pane {
  padding: 20px;
}

.imgs {
  display: flex;
}
.avatar-uploader {
  width: 200px;
  height: 200px;
  margin: 10px;
  display: inline-block;
  border: 1px solid silver;
  border-radius: 8px;
  position: relative;
  text-align: center;
  align-items: center;
  display: flex;
  justify-content: center;
  &.add-btn {
    border-width: 0;
    /deep/ .el-upload {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 8px;
}
.avatar-uploader .el-upload {
  border-radius: 8px;
  border: 1px dashed #d9d9d9 !important;
}

.add-icon {
  font-size: 40px;
}
.del-icon {
  font-size: 28px;
  position: absolute;
  top: 5px;
  right: 5px;
  margin: 0 auto;
  z-index: 1;
}
</style>
